package net.cmkj.mine.bean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.google.common.collect.Lists;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import net.cmkj.mine.bean.base.BaseSysRole;
import net.cmkj.mine.common.cache.CacheClearUtils;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.common.model.ZtreeView;
import net.cmkj.mine.util.BeanUtils;
import net.cmkj.mine.util.CommonUtils;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class SysRole extends BaseSysRole<SysRole> {

	public static final SysRole dao = new SysRole().dao();
	
	private static Logger log = LogManager.getLogger(SysRole.class);
	
	public List<SysRole> getSysRoleIdList(int uid){
		return this.find("select id from sys_role where id in(select role_id from sys_user_role where user_id =?)",uid);
	}
	
	public InvokeResult getZtreeViewList(Integer type, Integer roleId) {
		List<SysRes> curMenulist = this.getSysMenus(roleId);
		List<ZtreeView> ztreeViews = new ArrayList<ZtreeView>();
		ztreeViews.add(new ZtreeView(10000,null,"资源列表",true));
		for(SysRes SysRes : curMenulist){
			ZtreeView ztreeView=new ZtreeView();
			ztreeView.setId(SysRes.getInt("id"));
			ztreeView.setName(SysRes.getStr("name"));
			ztreeView.setOpen(true);
			if(SysRes.getInt("pid")==null){
				ztreeView.setpId(10000);
			}else{
				ztreeView.setpId(SysRes.getInt("pid"));
			}
			ztreeView.setChecked(SysRes.getLong("selected")==1?true:false);
			ztreeViews.add(ztreeView);
		}
		return InvokeResult.success(JsonKit.toJson(ztreeViews));
	}
	
	public InvokeResult getRoleZtreeViewList(Integer uid) {
		List<SysRole> list = this.getSysRoles(uid);
		List<ZtreeView> ztreeViews=new ArrayList<ZtreeView>();
		ztreeViews.add(new ZtreeView(10000,null,"角色列表",true));
		for(SysRole role : list){
			ZtreeView ztreeView=new ZtreeView();
			ztreeView.setId(role.getId());
			ztreeView.setName(role.getName());
			ztreeView.setOpen(true);
			ztreeView.setpId(10000);
			ztreeView.setChecked(role.getLong("selected")==1?true:false);
			ztreeViews.add(ztreeView);
		}
		return InvokeResult.success(JsonKit.toJson(ztreeViews));
	}
	
	public List<SysRes> getSysMenus(Integer roleId) {
		SysRole role = this.findById(roleId); 
		if(role!=null){
			List<SysRes> list = SysRes.dao.find("select *,(case when re.id in (select rr.res_id from sys_role_res rr where rr.role_id="+roleId+" ) THEN 1 ELSE 0 END) as selected FROM sys_res re where re.status=1 order by seq");
			return list;
		}
		return Lists.newArrayList();
	}
	
	public List<SysRole> getSysRoles(Integer uid) {
		List<SysRole> list = this.find("select *,(case when re.id in (select rr.role_id from sys_user_role rr where rr.user_id="+uid+" ) THEN 1 ELSE 0 END) as selected FROM sys_role re where re.status=1 order by seq");
		return list;
	}
	
	/**
	 * 获取列表
	 * @param pageNumber
	 * @param pageSize
	 * @param name
	 * @param status
	 * @return
	 */
	public Page<SysRole> paginate(int pageNumber, int pageSize, String name, Integer status, String orderbyStr) throws Exception {
		log.info("获取列表");
		List<Object> params = new ArrayList<Object>();
		StringBuffer sqlExceptSelect=new StringBuffer("from sys_role t where 1=1");
		if(CommonUtils.isNotEmpty(name)){
			sqlExceptSelect.append(" and t.name like ?");
			params.add(name);
		}
		if(status != null){
			sqlExceptSelect.append(" and t.status=?");
			params.add(status);
		}
		sqlExceptSelect.append(" "+orderbyStr);
		return dao.paginate(pageNumber, pageSize, "SELECT t.* ", sqlExceptSelect.toString(), CommonUtils.listToArr(params));
	}
	
	/**
	 * 获取对象
	 * @param id
	 * @return
	 */
	public SysRole findById(long id) throws Exception {
		log.info("获取对象");
		return dao.findFirst("select * from sys_role where id=?", id);
	}
	
	public List<SysRole> getSysRoleNamelist(){
		return this.find("select id,name from sys_role where status = 1");
	}
	
	public String getRoleNames(String roleIds){
		String sql = "select group_concat(name) as roleNames from sys_role where id in("+roleIds+")";
		SysRole sysRole = this.findFirst(sql);
		if(sysRole != null){
			return sysRole.getStr("roleNames");
		}
		return "";
	}
	
	public InvokeResult saveMenu(Integer roleId, String menuIds) {
		if(roleId.equals(1)){
			return InvokeResult.failure("超级管理员不能被修改");
		}
		Db.update("delete from sys_role_res where role_id = ?", roleId);
		if(CommonUtils.isNotEmpty(menuIds)){
			List<String> sqlList=Lists.newArrayList();
			for(String id : menuIds.split(",")){
				if(CommonUtils.isNotEmpty(id)){
					if(!Integer.valueOf(id).equals(10000))
						sqlList.add("insert into sys_role_res (role_id,res_id) values ("+roleId+","+Integer.valueOf(id)+")");
				}
			}
			Db.batch(sqlList, 50);
			CacheClearUtils.clearUserMenuCache();
		}
		return InvokeResult.success();
	}
	
	public InvokeResult save(Integer id, String name, Integer seq, String des) throws Exception {
		if(id!=null){
			SysRole role=this.findById(id);
			role.set("name", name).set("seq", seq).set("des",des).update();
		}else{
			new SysRole().set("name", name).set("seq", seq).set("des",des).set("createdate", new Date()).save();
		}
		return InvokeResult.success();
	}
	
	/**
	 * 对象保存
	 * @param model
	 * @return
	 */
	@Before(Tx.class)
	public InvokeResult save(SysRole model) throws Exception {
		log.info("对象保存");
	    boolean flag = false;
		if (null == model.getId()) {
			flag = model.save();
		} else {
			SysRole src = model.findById(model.getId());
			log.info(BeanUtils.compare(src, model));
			flag = model.update();
		}
		if (flag) {
			return InvokeResult.success();
		} else {
			return InvokeResult.failure("对象保存失败！");
		}
	}
	
	/**
	 * 对象删除
	 * @param ids
	 * @return
	 */
	@Before(Tx.class)
	public InvokeResult deleteByIds(String ids) throws Exception{
		log.info("对象删除");
    	String idarr[] = ids.split(",");
    	for (String id : idarr) {
    		if (!dao.findById(id).delete()) {
    			log.error("批量删除失败！");
    			throw new RuntimeException(id+"批量删除失败");
    		}
    	}
    	return InvokeResult.success();
	}
	
	public InvokeResult setVisible(Integer id, Integer visible) throws Exception {
		SysRole sysRole=this.findById(id);
		sysRole.set("status", visible).update();
		return InvokeResult.success();
	}
	
	/**
	 * 修改对象状态
	 * @param ids
	 * @return
	 */
	@Before(Tx.class)
	public InvokeResult setStatus(String ids, Integer status) throws Exception{
		log.info("对象状态变更");
		String idarr[] = ids.split(",");
    	for(String id : idarr){
    		if (!dao.findById(id).set("status", status).update()) {
    			log.error("对象批量状态变更失败！");
    			throw new RuntimeException(id+"状态批量变更失败！");
    		}
		}
		return InvokeResult.success();
	}
}
